<template>
    <view>
        <!-- 微信小程序环境 -->
        <!-- <view class='status'></view> -->

        <form @submit="formSubmit" report-submit='true'>
            <view class='addAddress pad30'>
                <view class='list borRadius14'>
                    <view class='item acea-row row-between-wrapper' style="border: none;">
                        <view class='name'>姓名</view>
                        <input type='text' placeholder='请输入姓名' placeholder-style="color:#ccc;" name='realName'
                            :value="userAddress.realName" placeholder-class='placeholder' maxlength="22" />
                    </view>
                    <view class='item acea-row row-between-wrapper'>
                        <view class='name'>联系电话</view>
                        <input type='number' placeholder='请输入联系电话' placeholder-style="color:#ccc;" name="phone"
                            :value='userAddress.phone' placeholder-class='placeholder' maxlength="11" />
                    </view>
                    <view class='item acea-row row-between-wrapper relative'>
                        <view class='name'>所在地区</view>
                        <view class="address">
                            <picker mode="multiSelector" @change="bindRegionChange"
                                @columnchange="bindMultiPickerColumnChange" :value="valueRegion" :range="multiArray">
                                <view class='acea-row' style="width: 100%;">
                                    <view class="picker line1">{{ region[0] }}，{{ region[1] }}，{{ region[2] }}</view>
                                    <view class='iconfont icon-xiangyou abs_right'></view>
                                </view>
                            </picker>
                        </view>
                    </view>
                    <view class='item acea-row row-between-wrapper relative' style="display: flex;height:auto">
                        <view class='name'>详细地址</view>
                        <div class="asdfs" style="display: flex;">
                            <textarea style="max-width:490rpx;line-height:1.5" type='text' placeholder='请填写具体地址' placeholder-style="color:#ccc;" name='detail'
                                placeholder-class='placeholder' v-model='userAddress.detail' />
                            <!-- <u-icon @tap="chooseLocation" name="map-fill" color="red" size="38"></u-icon> -->
                        </div>
                    </view>
                </view>
                <view class='default acea-row row-middle borRadius14'>
                    <checkbox-group @change='ChangeIsDefault'>
                        <checkbox :checked="userAddress.isDefault" />设置为默认地址
                    </checkbox-group>
                </view>

                <button class='keepBnt bg-color' form-type="submit">立即保存</button>
                <!-- 微信小程序环境 -->
                <!-- <view class="wechatAddress" v-if="!id" @click="getWxAddress">导入微信地址</view> -->
            </view>
        </form>
    </view>
</template>
<script>
import { editAddress, getAddressDetail, getCity } from '../../../utils/api/user.js';

let app = getApp();
export default {
    data() {
        return {
            regionDval: ['浙江省', '杭州市', '滨江区'],
            id: 0,
            userAddress: {
                isDefault: false
            },
            region: ['山东省', '聊城市', '东昌府区'],
            valueRegion: [0, 0, 0],
            district: [],
            multiArray: [],
            multiIndex: [0, 0, 0],
            cityId: 0,
        };
    },
    onLoad(options) {
        this.id = options.id || 0;
        uni.setNavigationBarTitle({
            title: options.id ? '修改地址' : '添加地址'
        })
        this.getUserAddress();
        this.getCityList();
    },
    methods: {
        getCityList() {
            getCity().then(res => {
                this.district = res.data;
                this.initialize();
            })
        },
        initialize() {
            let province = [], city = [], area = [];
            if (this.district.length) {
                let cityChildren = this.district[0].child || [];
                let areaChildren = cityChildren.length ? (cityChildren[0].child || []) : [];
                this.district.forEach(item => province.push(item.name));
                cityChildren.forEach(item => city.push(item.name));
                areaChildren.forEach(item => area.push(item.name));
                this.multiArray = [province, city, area];
            }
        },
        bindRegionChange(e) {
            let value = e.detail.value;
            this.region = [this.multiArray[0][value[0]], this.multiArray[1][value[1]], this.multiArray[2][value[2]]];
            this.cityId = this.district[value[0]].child[value[1]].cityId;
        },
        bindMultiPickerColumnChange(e) {
            let that = this,
                column = e.detail.column,
                value = e.detail.value,
                currentCity = this.district[value] || {
                    child: []
                },
                multiArray = that.multiArray,
                multiIndex = that.multiIndex;
            multiIndex[column] = value;
            switch (column) {
                case 0:
                    let areaList = currentCity.child[0] || {
                        child: []
                    };
                    multiArray[1] = currentCity.child.map((item) => {
                        return item.name;
                    });
                    multiArray[2] = areaList.child.map((item) => {
                        return item.name;
                    });
                    break;
                case 1:
                    let cityList = that.district[multiIndex[0]].child[multiIndex[1]].child || [];
                    multiArray[2] = cityList.map((item) => {
                        return item.name;
                    });
                    break;
                case 2:

                    break;
            }

            this.$set(this.multiArray, 2, multiArray[2]);

            this.multiArray = multiArray;

        },
        getUserAddress() {
            if (!this.id) return false;
            getAddressDetail(this.id).then(res => {
                let region = [res.data.province, res.data.city, res.data.district];
                this.userAddress = res.data;
                this.region = region;
                this.cityId = res.data.cityId;
            });
        },
        chooseLocation() {
            uni.chooseLocation({
                success: (res) => {
                    console.log("🚀 ~ chooseLocation ~ res.address:", res.address)

                    this.userAddress.detail = res.address.replace(/.+?(省|市|自治区|自治州|县|区)/g, '');
                    console.log("🚀 ~ chooseLocation ~ this.userAddress.detail:", this.userAddress.detail)
                    this.$forceUpdate()
                }
            })
        },
        getWxAddress() {
            console.log("🚀 ~ getWxAddress ~ getWxAddress:")
            
            uni.authorize({
                scope: 'scope.address',
                success() {
                    uni.chooseAddress({
                        success: (res) => {
                            let addressP = {
                                province: res.provinceName,
                                city: res.cityName,
                                district: res.countyName,
                                cityId: 0
                            };
                            editAddress({
                                address: addressP,
                                isDefault: 1,
                                realName: res.userName,
                                postCode: res.postalCode,
                                phone: res.telNumber,
                                detail: res.detailInfo,
                                id: 0
                            }).then(() => {
                                uni.showToast({
                                    title: '添加成功',
                                    icon: 'none'
                                });
                            }).catch(err => {
                                uni.showToast({
                                    title: err,
                                    icon: 'none'
                                });
                            });
                        },
                        fail: (err) => {
                            if (err.errMsg === 'chooseAddress:cancel') {
                                uni.showToast({
                                    title: '取消选择',
                                    icon: 'none'
                                });
                            }
                        }
                    });
                },
                fail() {
                    uni.showModal({
                        title: '您已拒绝导入微信地址权限',
                        content: '是否进入权限管理，调整授权？',
                        success(res) {
                            if (res.confirm) {
                                uni.openSetting();
                            } else if (res.cancel) {

                                uni.showToast({
                                    title: '已取消！',
                                    icon: 'none'
                                });
                            }
                        }
                    })
                }
            });
        },
        formSubmit(e) {
            let value = e.detail.value;
            if (!value.realName) {
                return uni.showToast({
                    title: '请填写收货人姓名',
                    icon: 'none'
                });
            }
            if (!value.phone) return uni.showToast({
                title: '请填写联系电话',
                icon: 'none'
            });
            if (!/^1(3|4|5|7|8|9|6)\d{9}$/i.test(value.phone)) return uni.showToast({
                title: '请输入正确的手机号码',
                icon: 'none'
            });
            if (this.region[0] == '省' || this.region == '' || this.region == undefined || this.region.length < 2) return uni.showToast({
                title: '请选择所在地区',
                icon: 'none'
            });
            if (!value.detail) return uni.showToast({
                title: '请填写详细地址',
                icon: 'none'
            });
            value.id = this.id;
            let regionArray = this.region;
            value.address = {
                province: regionArray[0],
                city: regionArray[1],
                district: regionArray[2],
                cityId: this.cityId,
            };
            value.isDefault = this.userAddress.isDefault;

            uni.showLoading({
                title: '保存中',
                mask: true
            })
            editAddress(value).then(res => {
                if (res.code == 200) {
                    if (this.id) {
                        uni.showToast({
                            title: '保存成功',
                            icon: 'success'
                        });
                        uni.hideLoading()
                    }
                    else {
                        uni.showToast({
                            title: '添加成功',
                            icon: 'success'
                        });
                        uni.hideLoading()
                    } uni.hideLoading()

                    setTimeout(function () {
                        uni.navigateBack();
                    }, 1000);

                } else {
                    uni.showToast({
                        title: '添加失败',
                        icon: 'error'
                    });
                    uni.hideLoading()
                }
            }).catch(err => {
                return uni.showToast({
                    title: err,
                    icon: 'success'
                });
            })
        },
        ChangeIsDefault(e) {
            this.userAddress.isDefault = !this.userAddress.isDefault;
        }
    }
}
</script>
<style scoped lang="scss">
/* 页面整体样式 */
.addAddress {
    padding-top: 20rpx;
}

/* 地址表单容器 */
.addAddress .list {
    background-color: #fff;
    padding: 0 24rpx;
}

/* 每个表单项的样式 */
.addAddress .list .item {
    border-top: 1rpx solid #eee;
    height: 90rpx;
    line-height: 90rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

/* 每个表单项中标签的样式 */
.addAddress .list .item .name {
    font-size: 30rpx;
    color: #333;
    flex: 1;
}

/* 每个表单项中输入框的样式 */
.addAddress .list .item input {
    width: 475rpx;
    font-size: 30rpx;
    font-weight: 400;
    border: none;
    padding: 10rpx;
}

/* 输入框的placeholder样式 */
.addAddress .list .item .placeholder {
    color: #ccc;
}

/* 区域选择器的样式 */
.addAddress .list .item picker .picker {
    width: 410rpx;
    font-size: 30rpx;
}

/* 地址选择框的样式 */
.addAddress .list .item .address {
    width: 475rpx;
    font-size: 30rpx;
    font-weight: 400;
    border: none;
    padding: 10rpx;
    text-align: left;
    line-height: 47rpx;
}

/* 详细地址框的样式 */
.addAddress .list .item .relative {
    position: relative;
}

/* 地址选择框右侧图标样式 */
.addAddress .list .item .iconfont.icon-dizhi {
    font-size: 44rpx;
    color: #007aff;
    position: absolute;
    right: 0;
    top: 50%;
    transform: translateY(-50%);
}

/* 设置为默认地址的样式 */
.addAddress .default {
    padding: 0 30rpx;
    height: 90rpx;
    background-color: #fff;
    margin-top: 23rpx;
    display: flex;
    align-items: center;
    justify-content: flex-start;
}

/* 默认地址的checkbox样式 */
.addAddress .default checkbox {
    margin-right: 15rpx;
}

/* 提交按钮的样式 */
.addAddress .keepBnt {
    width: 690rpx;
    height: 86rpx;
    border-radius: 50rpx;
    text-align: center;
    line-height: 86rpx;
    margin: 80rpx auto 24rpx auto;
    font-size: 32rpx;
    color: #fff;
    background-color: #007aff;
    border: none;
}

/* 微信地址导入按钮的样式 */
.addAddress .wechatAddress {
    width: 690rpx;
    height: 86rpx;
    border-radius: 50rpx;
    text-align: center;
    line-height: 86rpx;
    margin: 0 auto;
    font-size: 32rpx;
    color: #E93323;
    border: 1px solid #E93323;
}

/* 状态栏占位样式 */
.status {
    display: flex;
    width: 750rpx;
    height: var(--status-bar-height);
    background-color: #E93323;
    /* 状态栏背景色 */
}

/* 适配iPhone X等刘海屏状态 */
@media screen and (max-width: 750rpx) {
    .status {
        height: calc(var(--status-bar-height) + 20rpx);
    }
}
</style>
